const http = require('http');
const fs = require('fs');
const path = require('path');
const https = require('https');

// 修改为https模块
function downloadImage(url, savePath) {
  return new Promise((resolve, reject) => {
    const fileStream = fs.createWriteStream(savePath);
    
    // 添加请求头
    const options = {
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
      }
    };

    https.get(url, options, (response) => {
      // 处理重定向
      if (response.statusCode === 301 || response.statusCode === 302) {
        return downloadImage(response.headers.location, savePath);
      }

      if (response.statusCode !== 200) {
        reject(new Error(`请求失败，状态码：${response.statusCode}`));
        return;
      }

      response.pipe(fileStream);

      fileStream.on('finish', () => {
        fileStream.close();
        resolve();
      });
    }).on('error', (err) => {
      fs.unlink(savePath, () => {});
      reject(err);
    });
  });
}

// 使用示例
const imageUrl = 'https://mms0.baidu.com/it/u=3650186169,2479845496&fm=253&app=138&f=JPEG?w=751&h=500';
const savePath = path.join(__dirname, 'downloaded_image.jpg');

downloadImage(imageUrl, savePath)
  .then(() => {
    console.log('图片下载成功！');
  })
  .catch((err) => {
    console.error('图片下载失败：', err.message);
  });
